package com.edgclub.edg.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.VolleyError;
import com.edgclub.edg.GuZhiApplication;
import com.edgclub.edg.R;
import com.edgclub.edg.api.ResultCode;
import com.edgclub.edg.api.TopicApi;
import com.edgclub.edg.api.param.PostsParam;
import com.edgclub.edg.constant.BBConstant;
import com.edgclub.edg.event.BroadCastEvent;
import com.edgclub.edg.event.EventBus;
import com.edgclub.edg.http.VolleyListener;
import com.edgclub.edg.model.TopicChannel;
import com.edgclub.edg.model.result.TopicChannelData;
import com.edgclub.edg.uc.PagerSlidingTabStrip;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.JsonUtil;
import com.edgclub.edg.utils.util.TopicPrefUtils;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.squareup.otto.ThreadEnforcer;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 频道切换
 */
public class BBChannelFragment extends GzBaseFragment {
	private ViewPager pager;
	private PagerSlidingTabStrip tabs;
	private MyPagerAdapter adapter;

	private UserPrefUtils userPrefUtils;
	private TopicPrefUtils topicPrefUtils;
	private ArrayList<BBFragment> fragmentList;
	private ArrayList<TopicChannel> channelList;

	private TopicApi topicApi;

	public static String jump_channelId;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_bb_channel, container, false);
		initView(view);
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		initData();
	}
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		 super.onResume();
//		if(null!=tabs){
//			tabs.setIndicatorColorResource((Integer) SkinManager.getInstance().getResourceManager().getmResources(getActivity(),"skin_c5", R.color.skin_c5,2));
//			tabs.setTextColor((Integer) SkinManager.getInstance().getResourceManager().getmResources(getActivity(),"skin_c5", R.color.skin_c5,2));
//		}
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		if (isVisibleToUser) {
			MobclickAgent.onEvent(getActivity(),"EC_BB_FLOW");
		}
	}

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
				ThreadEnforcer.MAIN).register(this);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		EventBus.getEventBus(BroadCastEvent.EVENTBUS_COMMON,
				ThreadEnforcer.MAIN).unregister(this);
	}

	private void initView(View view){
		initLoadView(view);
		pager = (ViewPager) view.findViewById(R.id.viewpager2);
		tabs = (PagerSlidingTabStrip)view.findViewById(R.id.tabs);
//		tabs.setIndicatorColorResource((Integer) SkinManager.getInstance().getResourceManager().getmResources(getActivity(),"skin_c5",R.color.skin_c5,2),register_1);

		adapter = new MyPagerAdapter(getChildFragmentManager());
		pager.setAdapter(adapter);
		tabs.setViewPager(pager);
		final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources()
				.getDisplayMetrics());
		pager.setPageMargin(pageMargin);
//		pager.setCurrentItem(0);

		tabs.setOnTabReselectedListener(new PagerSlidingTabStrip.OnTabReselectedListener() {
			@Override
			public void onTabReselected(int position) {
//				Toast.makeText(getActivity(), "Tab reselected: " + position, Toast.LENGTH_SHORT).show();
			}
		});
		tabs.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

			}

			@Override
			public void onPageSelected(int position) {
				if(position==0){
					MobclickAgent.onEvent(getActivity(),"EC_BB_FLOW_TAB_ALL");
				} else if (position == 1) {
					MobclickAgent.onEvent(getActivity(),"EC_BB_FLOW_TAB_FOLLOW");
				}else{
					//统计点击事件
					HashMap<String,String> map = new HashMap<String,String>();
					map.put("title",channelList.get(position).getTitle()+"");
					MobclickAgent.onEvent(getActivity(), "EC_BB_FLOW_TAB_CHANNEL", map);
				}
			}

			@Override
			public void onPageScrollStateChanged(int state) {

			}
		});

	}

	private void initData(){
		topicApi = new TopicApi(getActivity());
		userPrefUtils = new UserPrefUtils(getActivity());
		topicPrefUtils = new TopicPrefUtils(getActivity());
		fragmentList = new ArrayList<>();
		try {
			getChannelPost();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	private void getChannelPost() {
		PostsParam param = new PostsParam();
		try {
			param.setUserId(userPrefUtils.getUser().getId() + "");

		topicApi.channelPost(param, new getChannelListener());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	class getChannelListener implements VolleyListener {

		@Override
		public void onStart(String tag) {
		}

		@Override
		public void onSuccess(String response,String tag) {
			if (JSONHelper.isSuccess(response)) {
				TopicChannelData data = JsonUtil.getMode(response,
						TopicChannelData.class);
				channelList = data.getData();
				if (channelList.size() > 0){
					GuZhiApplication.getInstance().setChannelList(channelList);
				}
				TopicChannel channelTmp = new TopicChannel();
				channelTmp.setChannelId(BBConstant.channel_all);
				channelTmp.setTitle("全部");
				TopicChannel channelTmp1 = new TopicChannel();
				channelTmp1.setChannelId(BBConstant.channel_attention);
				channelTmp1.setTitle("我关注的");
				channelList.add(0, channelTmp);
				channelList.add(1, channelTmp1);
				pager.setOffscreenPageLimit(channelList.size());
				if (channelList != null) {
					for(int i=0;i<channelList.size();i++){
						fragmentList.add(BBFragment.newInstance(BBConstant.TOPIC_TYPE_CHANNEL, channelList.get(i)));
					}
					adapter.setList(channelList);
					adapter.setFragmentList(fragmentList);
//					pager.setAdapter(adapter);
//					tabs.setViewPager(pager);
					adapter.notifyDataSetChanged();
					pager.setCurrentItem(0);

					topicPrefUtils.seTopicChannel(response); //保存频道
				}
				setLoadViewGONE();
			}
		}

		@Override
		public void onFaile(VolleyError volleyError,String tag) {
			setNoNetWork(new ReLoadClickListener() {
				@Override
				public void reload() {
					getChannelPost();
				}
			});
			ResultCode.toastVolleyError(getActivity(), volleyError);
		}
	}


	public class MyPagerAdapter extends FragmentPagerAdapter {

		private List<TopicChannel> list = new ArrayList<TopicChannel>();
		ArrayList<BBFragment> fragmentList;

		public MyPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return list.get(position).getTitle();
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public BBFragment getItem(int position) {
			return fragmentList.get(position);
		}

		public void setList(List<TopicChannel> list) {
			this.list = list;
		}

		public void setFragmentList(ArrayList<BBFragment> fragmentList) {
			this.fragmentList = fragmentList;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		try {
			int i = pager.getCurrentItem();
			if(adapter.getItem(i)!=null){
                adapter.getItem(i).onActivityResult(requestCode, resultCode, data);
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
